import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.conf import settings


class CheckPermission(MiddlewareMixin):
    def process_request(self, request):
        current_url = request.path_info

        if current_url == '/':
            return None
        for valid_url in settings.VALID_URL_LIST:
            if re.match(valid_url, current_url):
                return None

        permissions_dict = request.session.get(settings.SESSION_PERMISSION_KEY)
        if not permissions_dict:
            return HttpResponse('访问的地址不存在')

        for item in permissions_dict.values():
            i_url = '^%s$' % item['url']
            if re.match(i_url, current_url):
                # start 生成导航路径
                show_route_list = [{'title': '首页', 'url': '#'}]
                if item['p_title']:
                    show_route_list.extend([{'title': item['p_title'], 'url': item['p_url']},
                                            {'title': item['title'], 'url': None}
                                            ])
                else:
                    show_route_list.append({'title': item['title'], 'url': None})

                request.route_list = show_route_list
                # end
                return None

        return HttpResponse('没有访问权限')
